package com.nh.glory.admin.modular.system.controller;

import com.nh.glory.core.R;
import com.nh.glory.core.node.INode;
import com.nh.glory.core.util.Func;
import com.nh.glory.data.model.Dict;
import com.nh.glory.data.vo.DictVO;
import com.nh.glory.ware.service.system.DictService;
import com.nh.glory.ware.support.Condition;
import com.nh.glory.ware.wrapper.DictWrapper;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("/dict")
public class DictController {

	private DictService dictService;

	/**
	 * 详情
	 */
	@GetMapping("{id}")
	public R<DictVO> detail(@PathVariable Integer id) {
		Dict detail = dictService.getById(id);
		DictWrapper dictWrapper = new DictWrapper(dictService);
		return R.ok(dictWrapper.entityVO(detail));
	}

	/**
	 * 列表
	 */
	@GetMapping
	public R<List<INode>> list(@RequestParam Map<String, Object> dict) {
		List<Dict> list = dictService.list(Condition.getQueryWrapper(dict, Dict.class).lambda().orderByAsc(Dict::getSort));
		DictWrapper dictWrapper = new DictWrapper(dictService);
		return R.ok(dictWrapper.listNodeVO(list));
	}

	/**
	 * 获取字典树形结构
	 *
	 * @return
	 */
	@GetMapping("/tree")
	public R<List<DictVO>> tree() {
		List<DictVO> tree = dictService.tree();
		return R.ok(tree);
	}

	/**
	 * 新增或修改
	 */
	@PostMapping
	public R submit(@Valid @RequestBody Dict dict) {
		if(dict.getId() == null) {
			if(dict.getParentId() == null) dict.setParentId(0L);
			if(dict.getDeleted() == null) dict.setDeleted(0);
		}
		return R.status(dictService.submit(dict));
	}


	/**
	 * 删除
	 */
	@DeleteMapping
	@CacheEvict(cacheNames = {DictService.DICT_LIST, DictService.DICT_VALUE})
	public R remove(@RequestParam String ids) {
		return R.status(dictService.removeByIds(Func.toIntList(ids)));
	}

	/**
	 * 获取字典
	 */
	@GetMapping("/dictionary")
	public R<List<Dict>> dictionary(String code) {
		List<Dict> tree = dictService.getList(code);
		return R.ok(tree);
	}


}
